package club.bigtian.agent;

import com.intellij.notification.Notification;
import com.intellij.notification.NotificationAction;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.startup.StartupActivity;
import org.jetbrains.annotations.NotNull;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;

/**
 * JavaAgent自动安装器
 * 在IDEA启动时自动配置augment-privacy-agent到javaagent参数
 */
public class JavaAgentInstaller implements StartupActivity {
    
    private static final Logger LOG = Logger.getInstance(JavaAgentInstaller.class);
    private static final String AGENT_JAR_NAME = "augment-privacy-agent-1.0.0.jar";
    private static final String AGENT_MARKER = "-javaagent:";
    private static final String AGENT_IDENTIFIER = "augment-privacy-agent";
    
    @Override
    public void runActivity(@NotNull Project project) {
        // 在后台线程中执行，避免阻塞启动
        ApplicationManager.getApplication().executeOnPooledThread(() -> {
            try {
                installJavaAgent(project);
            } catch (Exception e) {
                LOG.error("Failed to install JavaAgent", e);
            }
        });
    }
    
    /**
     * 安装JavaAgent
     */
    private void installJavaAgent(Project project) {
        try {
            // 1. 复制agent jar到固定位置
            Path agentPath = copyAgentJarToConfigDir();
            if (agentPath == null) {
                LOG.warn("Failed to copy agent jar");
                return;
            }
            
            // 2. 检查vmoptions文件
            Path vmOptionsPath = getVmOptionsPath();
            if (vmOptionsPath == null) {
                LOG.warn("Could not find vmoptions file");
                showManualInstallNotification(project, agentPath);
                return;
            }
            
            // 3. 检查是否已经配置了javaagent
            if (isAgentAlreadyConfigured(vmOptionsPath)) {
                LOG.info("JavaAgent already configured");
                return;
            }
            
            // 4. 添加javaagent配置
            boolean success = addAgentToVmOptions(vmOptionsPath, agentPath);
            if (success) {
                showRestartNotification(project);
            } else {
                showManualInstallNotification(project, agentPath);
            }
            
        } catch (Exception e) {
            LOG.error("Error installing JavaAgent", e);
        }
    }
    
    /**
     * 复制agent jar到配置目录
     */
    private Path copyAgentJarToConfigDir() {
        try {
            // 目标目录：IDEA配置目录/augment-agent/
            String configPath = PathManager.getConfigPath();
            Path agentDir = Paths.get(configPath, "augment-agent");
            Files.createDirectories(agentDir);
            
            Path targetPath = agentDir.resolve(AGENT_JAR_NAME);
            
            // 如果文件已存在，检查是否需要更新
            if (Files.exists(targetPath)) {
                LOG.info("Agent jar already exists: " + targetPath);
                return targetPath;
            }
            
            // 从resources复制jar文件
            InputStream inputStream = getClass().getClassLoader()
                    .getResourceAsStream(AGENT_JAR_NAME);
            
            if (inputStream == null) {
                LOG.error("Could not find agent jar in resources: " + AGENT_JAR_NAME);
                return null;
            }
            
            Files.copy(inputStream, targetPath, StandardCopyOption.REPLACE_EXISTING);
            inputStream.close();
            
            LOG.info("Agent jar copied to: " + targetPath);
            return targetPath;
            
        } catch (Exception e) {
            LOG.error("Failed to copy agent jar", e);
            return null;
        }
    }
    
    /**
     * 获取vmoptions文件路径
     */
    private Path getVmOptionsPath() {
        try {
            String configPath = PathManager.getConfigPath();
            String os = System.getProperty("os.name").toLowerCase();
            
            // 根据不同平台确定vmoptions文件名
            String vmOptionsFileName;
            if (os.contains("win")) {
                vmOptionsFileName = "idea64.exe.vmoptions";
            } else if (os.contains("mac")) {
                vmOptionsFileName = "idea.vmoptions";
            } else {
                vmOptionsFileName = "idea64.vmoptions";
            }
            
            Path vmOptionsPath = Paths.get(configPath, vmOptionsFileName);
            
            // 如果文件不存在，尝试创建
            if (!Files.exists(vmOptionsPath)) {
                LOG.info("Creating new vmoptions file: " + vmOptionsPath);
                Files.createFile(vmOptionsPath);
            }
            
            return vmOptionsPath;
            
        } catch (Exception e) {
            LOG.error("Failed to get vmoptions path", e);
            return null;
        }
    }
    
    /**
     * 检查是否已经配置了agent
     */
    private boolean isAgentAlreadyConfigured(Path vmOptionsPath) {
        try {
            if (!Files.exists(vmOptionsPath)) {
                return false;
            }
            
            List<String> lines = Files.readAllLines(vmOptionsPath);
            for (String line : lines) {
                if (line.trim().startsWith(AGENT_MARKER) && 
                    line.contains(AGENT_IDENTIFIER)) {
                    return true;
                }
            }
            return false;
            
        } catch (Exception e) {
            LOG.error("Failed to check vmoptions", e);
            return false;
        }
    }
    
    /**
     * 添加agent配置到vmoptions
     */
    private boolean addAgentToVmOptions(Path vmOptionsPath, Path agentPath) {
        try {
            List<String> lines = new ArrayList<>();
            
            // 读取现有内容
            if (Files.exists(vmOptionsPath)) {
                lines = new ArrayList<>(Files.readAllLines(vmOptionsPath));
            }
            
            // 添加javaagent配置
            String agentLine = AGENT_MARKER + agentPath.toString().replace("\\", "/");
            lines.add(agentLine);
            
            // 写回文件
            Files.write(vmOptionsPath, lines);
            
            LOG.info("Added javaagent to vmoptions: " + agentLine);
            return true;
            
        } catch (Exception e) {
            LOG.error("Failed to add agent to vmoptions", e);
            return false;
        }
    }
    
    /**
     * 显示重启通知
     */
    private void showRestartNotification(Project project) {
        ApplicationManager.getApplication().invokeLater(() -> {
            Notification notification = new Notification(
                    "Augment Privacy Agent",
                    "JavaAgent已配置",
                    "augment-privacy-agent已添加到IDEA启动参数中。\n请重启IDEA以使配置生效。",
                    NotificationType.INFORMATION
            );
            
            notification.addAction(new NotificationAction("稍后重启") {
                @Override
                public void actionPerformed(@NotNull AnActionEvent e, @NotNull Notification notification) {
                    notification.expire();
                }
            });
            
            notification.addAction(new NotificationAction("立即重启") {
                @Override
                public void actionPerformed(@NotNull AnActionEvent e, @NotNull Notification notification) {
                    ApplicationManager.getApplication().restart();
                }
            });
            
            Notifications.Bus.notify(notification, project);
        });
    }
    
    /**
     * 显示手动安装通知
     */
    private void showManualInstallNotification(Project project, Path agentPath) {
        ApplicationManager.getApplication().invokeLater(() -> {
            String message = String.format(
                    "无法自动配置JavaAgent。\n" +
                    "请手动在IDEA的VM选项中添加以下配置：\n" +
                    "-javaagent:%s\n\n" +
                    "配置位置：Help -> Edit Custom VM Options",
                    agentPath.toString()
            );
            
            Notification notification = new Notification(
                    "Augment Privacy Agent",
                    "需要手动配置JavaAgent",
                    message,
                    NotificationType.WARNING
            );
            
            Notifications.Bus.notify(notification, project);
        });
    }
}

